package com.example.asd.puzzle;

import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.List;

import puzzle.Puzzle;

import static com.example.asd.puzzle.MainActivity.str_myip;
import static com.example.asd.puzzle.MainActivity.str_server;

public class GameActivity extends AppCompatActivity {
    private ImageView d11,d12,d13,d21,d22,d23,d31,d32,d33;
    private List<ImageView> imageViewList=new ArrayList<>();
    private TextView tv_countRemains,tv_status;
    private EditText et_x,et_y;
    private Button bt_submit;
    private Handler handler=new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.arg1){
                case 0://Toast
                    Toast.makeText(GameActivity.this,msg.obj.toString(),Toast.LENGTH_SHORT).show();
                    break;
                case 1://Received yourTurn
                    bt_submit.setEnabled(true);
                    tv_status.setText("轮到你输入了");
                    break;
                case 2://Received end
                    try {
                        JSONObject object = (JSONObject) msg.obj;
                        String me = object.getString("Me");
                        String result=object.getString("Content");
                        String rip=object.getString("Info");
                        if(result.equals("win")){
                            View view=View.inflate(GameActivity.this,R.layout.page_result,null);
                            TextView t1=view.findViewById(R.id.result_timeLast),t2=view.findViewById(R.id.result_result);
                            t1.setText("");
                            t2.setText("大家都赢了");
                            new AlertDialog.Builder(GameActivity.this)
                                    .setTitle("游戏结果")
                                    .setView(view)
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            finish();
                                        }
                                    })
                                    .show();
                        }else if (rip.equals(str_myip)){
                            View view=View.inflate(GameActivity.this,R.layout.page_result,null);
                            TextView t1=view.findViewById(R.id.result_timeLast),t2=view.findViewById(R.id.result_result);
                            t1.setText("");
                            t2.setText("你输了");
                            new AlertDialog.Builder(GameActivity.this)
                                    .setTitle("游戏结果")
                                    .setView(view)
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            finish();
                                        }
                                    })
                                    .show();
                        }else {
                            View view=View.inflate(GameActivity.this,R.layout.page_result,null);
                            TextView t1=view.findViewById(R.id.result_timeLast),t2=view.findViewById(R.id.result_result);
                            t1.setText("你赢了");
                            t2.setText("输者是："+me);
                            new AlertDialog.Builder(GameActivity.this)
                                    .setTitle("游戏结果")
                                    .setView(view)
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            finish();
                                        }
                                    })
                                    .show();
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
                case 3://Received submit
                    apis_updateImageMap();
                    break;
                case 4://Update RoomInfo
                    try {
                        JSONObject jsonObject = (JSONObject) msg.obj;
                        JSONArray mapArray = jsonObject.getJSONArray("ImageMap");
                        for (int i=0;i<mapArray.length();i++){
                            float itemAlpha=mapArray.getInt(i)%2;
                            imageViewList.get(i).setAlpha(itemAlpha);
                        }
                        int countRemains=jsonObject.getInt("CountRemains");
                        tv_countRemains.setText("剩余次数："+countRemains);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
                case 5://Submit succeed
                    bt_submit.setEnabled(false);
                    tv_status.setText("其他玩家正在输入。。。");
                    break;
                case 6://checkResult
                    try {
                        JSONObject o = (JSONObject) msg.obj;
                        String timeLast = o.getString("Info");
                        JSONArray mapArray=o.getJSONObject("Data").getJSONArray("ImageMap");
                        String result;
                        if (didYouWin(mapArray)){
                            result="你们赢了";
                        }else {
                            result="你们输了";
                        }
                        View view=View.inflate(GameActivity.this,R.layout.page_result,null);
                        TextView t1=view.findViewById(R.id.result_timeLast),t2=view.findViewById(R.id.result_result);
                        t1.setText("总共耗时："+timeLast+"s");
                        t2.setText(result);
                        new AlertDialog.Builder(GameActivity.this)
                                .setTitle("游戏结果")
                                .setView(view)
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        finish();
                                    }
                                })
                                .show();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };



    private PushService.MyBinder binder;
    private OnMsgReceivedListener listenr=new OnMsgReceivedListener() {
        @Override
        public void onMsgReceived(JSONObject o) {
            try {
                String state=o.getString("State");
                if (state.equals("yourTurn")){
                    sendMsgWithArg1(1);
                }else if (state.equals("end")){
                    Message message=new Message();
                    message.arg1=2;
                    message.obj=o;
                    handler.sendMessage(message);
                }else if (state.equals("submit")){
                    apis_updateImageMap();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void toastMe(String str) {
            toastMe(str);
        }
    };
    private String str_roomName,str_roomOwner,TAG="TAG";
    private void apis_queryResult() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    JSONObject po=new JSONObject();
                    po.put("Info",str_roomName);
                    String str= Puzzle.doRequest("http://"+str_server+":8080/apis/getroominfo",po.toString());
                    Log.d(TAG, "run: getRoomInfo :"+str);
                    JSONObject o=(JSONObject)(new JSONTokener(str).nextValue());
                    if (o.getString("State").toString().equals("OK")){
                        JSONObject jsonObject=o.getJSONObject("Data");
                        Message message=new Message();
                        message.arg1=6;
                        message.obj=o;
                        handler.sendMessage(message);
                    }else{
                        Log.d(TAG, "run: getRoomList() failed :"+o.getString("Info").toString());
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void apis_updateImageMap() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    JSONObject po=new JSONObject();
                    po.put("Info",str_roomName);
                    String str= Puzzle.doRequest("http://"+str_server+":8080/apis/getroominfo",po.toString());
                    Log.d(TAG, "run: getRoomInfo :"+str);
                    JSONObject o=(JSONObject)(new JSONTokener(str).nextValue());
                    if (o.getString("State").toString().equals("OK")){
                        JSONObject jsonObject=o.getJSONObject("Data");
                        Message message=new Message();
                        message.arg1=4;
                        message.obj=jsonObject;
                        handler.sendMessage(message);
                    }else{
                        Log.d(TAG, "run: getRoomList() failed :"+o.getString("Info").toString());
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void apis_startGame() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject po=new JSONObject();
                    po.put("Info", str_roomName);
                    String str= Puzzle.doRequest("http://"+str_server+":8080/apis/startgame",po.toString());
                    JSONObject o=(JSONObject)(new JSONTokener(str).nextValue());
                    if (o.getString("State").toString().equals("OK")) {
                    }else {
                        toastMe(o.getString("Info"));
                        Log.d(TAG, "run: startGame failed "+str);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private boolean didYouWin(JSONArray mapArray) throws JSONException {
        for (int i=0;i<mapArray.length();i++){
            if (mapArray.getInt(i)%2!=1){
                return false;
            }
        }
        return true;
    }
    private void apis_submit(final String x, final String y){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    JSONObject object=new JSONObject();
                    object.put("Info",str_roomName);
                    object.put("Content",x);
                    object.put("Object",y);
                    String str=Puzzle.doRequest("http://"+str_server+":8080/apis/submit",object.toString());
                    Log.d(TAG, "run: submit backInfo:"+str);
                    JSONObject o= (JSONObject) new JSONTokener(str).nextValue();
                    if (o.getString("State").toString().equals("OK")){
                        sendMsgWithArg1(5);
                    }else{
                        Log.d(TAG, "run: "+o.getString("Info"));
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private ServiceConnection sc=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            binder=(PushService.MyBinder)iBinder;
            binder.setListener(listenr);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);
        str_roomName=RoomWaitingActivity.str_roomName;
        str_roomOwner=RoomWaitingActivity.str_roomOwner;
        initUI();
        pushConn();
        if (str_roomOwner.equals(str_myip))
            apis_startGame();
    }

    private void pushConn() {
        Intent intent=new Intent(GameActivity.this,PushService.class);
        bindService(intent,sc,BIND_AUTO_CREATE);
    }

    private void initUI() {
        d11=findViewById(R.id.d11);
        d12=findViewById(R.id.d12);
        d13=findViewById(R.id.d13);
        d21=findViewById(R.id.d21);
        d22=findViewById(R.id.d22);
        d23=findViewById(R.id.d23);
        d31=findViewById(R.id.d31);
        d32=findViewById(R.id.d32);
        d33=findViewById(R.id.d33);
        imageViewList.add(d11);
        imageViewList.add(d12);
        imageViewList.add(d13);
        imageViewList.add(d21);
        imageViewList.add(d22);
        imageViewList.add(d23);
        imageViewList.add(d31);
        imageViewList.add(d32);
        imageViewList.add(d33);
        tv_status=findViewById(R.id.game_tv_status);
        tv_countRemains =findViewById(R.id.game_tv_countRemains);
        et_x=findViewById(R.id.game_et_x);
        et_y=findViewById(R.id.game_et_y);
        bt_submit=findViewById(R.id.game_bt_submit);
        bt_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String x=et_x.getText().toString(),y=et_y.getText().toString();
                if (x!=null&&y!=null&&!x.equals("")&&!y.equals("")){
                    apis_submit(x,y);
                }
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(sc);
        apis_dropRoom();
    }

    private void apis_dropRoom() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject po=new JSONObject();
                    po.put("Info", str_roomName);
                    String str= Puzzle.doRequest("http://"+str_server+":8080/apis/droproom",po.toString());
                    JSONObject o=(JSONObject)(new JSONTokener(str).nextValue());
                    if (o.getString("State").toString().equals("OK")) {
                    }else {
                        toastMe(o.getString("Info"));
                        Log.d(TAG, "run: drop room failed "+str);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void toastMe(String str){
        Message message=new Message();
        message.arg1=0;
        message.obj=str;
        handler.sendMessage(message);
    }
    private void sendMsgWithArg1(int i){
        Message message=new Message();
        message.arg1=i;
        handler.sendMessage(message);
    }
}
